local extension = Package("sklegendary")
extension.extensionName = "jilvRem"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["sklegendary"] = "极略三国-传说",
  ["sk_le"] = "极略-传说",
}

local guanyu = General(extension, "sk_le__guanyu", "shu", 4)
local sk_le__wusheng = fk.CreateViewAsSkill{
  name = "sk_le__wusheng",
  anim_type = "offensive",
  pattern = "slash",
  prompt = "#sk_le__wusheng",
  card_filter = function(self, to_select, selected)
    return #selected == 0 and Fk:getCardById(to_select).color == Card.Red
  end,
  view_as = function(self, cards)
    if #cards ~= 1 then return end
    local card = Fk:cloneCard("slash")
    card.skillName = self.name
    card:addSubcard(cards[1])
    return card
  end,
}
local sk_le__wusheng_trigger = fk.CreateTriggerSkill{
  name = "#sk_le__wusheng_trigger",
  mute = true,
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(sk_le__wusheng) and
      data.card.trueName == "slash" and table.contains(data.card.skillNames, "sk_le__wusheng")
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, "sk_le__wusheng")
    if player.dead or player:isKongcheng() then return end
    local cards = room:askForDiscard(player, 1, 3, false, "sk_le__wusheng", true, ".|.|.|hand", "#sk_le__wusheng-discard::"..data.to)
    local n = #cards
    if n > 0 then
      data.additionalDamage = (data.additionalDamage or 0) + n
      local to = room:getPlayerById(data.to)
      if not to.dead then
        room:askForDiscard(to, n, n, true, "sk_le__wusheng", false)
      end
      if not player.dead and player.phase == Player.Play then
        room:addPlayerMark(player, MarkEnum.SlashResidue.."-phase", n)
      end
    end
  end,
}
sk_le__wusheng:addRelatedSkill(sk_le__wusheng_trigger)
guanyu:addSkill(sk_le__wusheng)
Fk:loadTranslationTable{
  ["sk_le__guanyu"] = "关羽",
  ["#sk_le__guanyu"] = "水淹七军",

  ["sk_le__wusheng"] = "武圣",
  [":sk_le__wusheng"] = "你可以将红色牌当【杀】使用或打出。当你以此法使用【杀】指定目标后，你摸一张牌并弃置至多三张手牌，若如此做，"..
  "目标角色弃置X张牌，此【杀】伤害+X；若此时是你的出牌阶段，你于此阶段内使用【杀】次数上限+X。（X为你弃置的牌数）",
  ["#sk_le__wusheng"] = "武圣：将一张红色牌当【杀】使用或打出",
  ["#sk_le__wusheng_trigger"] = "武圣",
  ["#sk_le__wusheng-discard"] = "武圣：弃置至多三张手牌，令此【杀】伤害增加，且 %dest 需弃置等量的牌",

  ["$sk_le__wusheng1"] = "",
  ["$sk_le__wusheng2"] = "",
  ["~sk_le__guanyu"] = "",
}

local sunshangxiang = General(extension, "sk_le__sunshangxiang", "wu", 3, 3, General.Female)
local sk_le__jieyin = fk.CreateActiveSkill{
  name = "sk_le__jieyin",
  anim_type = "support",
  card_num = 1,
  target_num = 1,
  prompt = "#sk_le__jieyin",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter =function (self, to_select, selected, player)
    return #selected == 0 and not player:prohibitDiscard(to_select)
  end,
  target_filter =function (self, to_select, selected, selected_cards, card, extra_data, player)
    return #selected == 0 and to_select ~= player.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:throwCard(effect.cards, self.name, player, player)
    local yes = true
    if not player.dead then
      if player:isWounded() then
        room:recover({
          who = player,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        })
      else
        player:drawCards(2, self.name)
        yes = false
      end
    end
    if not target.dead then
      if target:isWounded() then
        room:recover({
          who = target,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        })
      else
        target:drawCards(2, self.name)
        yes = false
      end
    end
    if yes then
      player:setSkillUseHistory(self.name, 0, Player.HistoryPhase)
    end
  end,
}
local sk_le__xiaoji = fk.CreateTriggerSkill{
  name = "sk_le__xiaoji",
  anim_type = "drawcard",
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      for _, move in ipairs(data) do
        if move.from and move.from == player.id then
          for _, info in ipairs(move.moveInfo) do
            if info.fromArea == Card.PlayerEquip then
              return true
            end
          end
        end
      end
    end
  end,
  on_trigger = function(self, event, target, player, data)
    self.cancel_cost = false
    for _, move in ipairs(data) do
      if move.from and move.from == player.id then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerEquip then
            if not player:hasSkill(self) or self.cancel_cost then return end
            self.cost_data = info.cardId
            self:doCost(event, target, player, data)
          end
        end
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if player.room:askForSkillInvoke(player, self.name) then
      return true
    end
    self.cancel_cost = true
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:drawCards(1, self.name)
    if player.dead then return end
    local card = Fk:getCardById(self.cost_data)
    if card.sub_type == Card.SubtypeWeapon then
      if #room.alive_players == 1 then return end
      local to = room:askForChoosePlayers(player, table.map(room:getOtherPlayers(player), Util.IdMapper), 1, 1,
        "#sk_le__xiaoji-damage", self.name, true)
      if #to > 0 then
        room:damage({
          from = player,
          to = room:getPlayerById(to[1]),
          damage = 1,
          skillName = self.name,
        })
      end
    elseif card.sub_type == Card.SubtypeArmor or card.sub_type == Card.SubtypeTreasure then
      player:drawCards(2, self.name)
    elseif card.sub_type == Card.SubtypeOffensiveRide or card.sub_type == Card.SubtypeDefensiveRide then
      for i = 1, 2, 1 do
        local targets = table.map(table.filter(room:getOtherPlayers(player), function(p)
          return not p:isNude() end), Util.IdMapper)
        if player.dead or #targets == 0 then return end
        local to = room:askForChoosePlayers(player, targets, 1, 1, "#sk_le__xiaoji-discard", self.name, true)
        if #to > 0 then
          to = room:getPlayerById(to[1])
          local id = room:askForCardChosen(player, to, "he", self.name)
          room:throwCard(id, self.name, to, player)
        else
          return
        end
      end
    end
  end,
}
sunshangxiang:addSkill(sk_le__jieyin)
sunshangxiang:addSkill(sk_le__xiaoji)
Fk:loadTranslationTable{
  ["sk_le__sunshangxiang"] = "孙尚香",
  ["#sk_le__sunshangxiang"] = "绝代巾帼",

  ["sk_le__jieyin"] = "结姻",
  [":sk_le__jieyin"] = "出牌阶段限一次，你可以弃置一张牌并选择一名其他角色，你与其之中未受伤的角色摸两张牌，已受伤的角色回复1点体力。"..
  "若没有角色以此法摸牌，此技能视为未发动过。",
  ["sk_le__xiaoji"] = "枭姬",
  [":sk_le__xiaoji"] = "当你失去装备区内的一张牌后，你可以摸一张牌，然后根据失去牌的类型执行以下效果：武器牌，你可以对一名其他角色"..
  "造成1点伤害；防具牌或宝物牌，摸两张牌；坐骑牌，你可以依次弃置一至两名其他角色共计两张牌。",
  ["#sk_le__jieyin"] = "结姻：弃置一张牌选择一名角色，你与其未受伤的角色摸两张牌，已受伤的角色回复1点体力",
  ["#sk_le__xiaoji-damage"] = "枭姬：你可以对一名角色造成1点伤害",
  ["#sk_le__xiaoji-discard"] = "枭姬：你可以依次弃置一至两名角色的共计两张牌",

  ["$sk_le__jieyin1"] = "",
  ["$sk_le__jieyin2"] = "",
  ["$sk_le__xiaoji1"] = "",
  ["$sk_le__xiaoji2"] = "",
  ["~sk_le__sunshangxiang"] = "",
}

local zhenji = General(extension, "sk_le__zhenji", "wei", 3, 3, General.Female)
local sk_le__qingguo = fk.CreateTriggerSkill{
  name = "sk_le__qingguo",
  anim_type = "defensive",
  events = {fk.TargetConfirmed},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.from ~= player.id and
      (data.card.trueName == "slash" or data.card:isCommonTrick()) and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local card = player.room:askForDiscard(player, 1, 1, true, self.name, true, ".|.|spade,club|hand",
      "#sk_le__qingguo-discard::"..data.from..":"..data.card:toLogString(), true)
    if #card > 0 then
      self.cost_data = card[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data, self.name, player, player)
    table.insertIfNeed(data.nullifiedTargets, player.id)
    if player.dead or room:getPlayerById(data.from).dead or Fk:getCardById(self.cost_data).suit ~= Card.Spade then return end
    if room:askForSkillInvoke(player, self.name, nil, "#sk_le__qingguo-invoke::"..data.from) then
      room:doIndicate(player.id, {data.from})
      room:loseHp(room:getPlayerById(data.from), 1, self.name)
    end
  end,
}
local sk_le__luoshen = fk.CreateTriggerSkill{
  name = "sk_le__luoshen",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Start
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = {}
    local num = {}
    for i = 1, 13, 1 do
      table.insert(num, i)
    end
    while true do
      local judge = {
        who = player,
        reason = self.name,
        pattern = ".|"..table.concat(num, ","),
        skipDrop = true,
      }
      room:judge(judge)
      local card = judge.card
      table.insert(cards, card)
      if not table.removeOne(num, judge.card.number) then
        room:addPlayerMark(player, MarkEnum.AddMaxCardsInTurn, judge.card.number)
        break
      end
      if player.dead then
        break
      end
    end
    cards = table.filter(cards, function(c) return room:getCardArea(c.id) == Card.Processing end)
    if #cards > 0 then
      if player.dead then
        room:moveCardTo(cards, Card.DiscardPile, nil, fk.ReasonJustMove, self.name, nil, true)
      else
        room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
      end
    end
  end,
}
zhenji:addSkill(sk_le__qingguo)
zhenji:addSkill(sk_le__luoshen)
Fk:loadTranslationTable{
  ["sk_le__zhenji"] = "甄姬",
  ["#sk_le__zhenji"] = "似水莲华",

  ["sk_le__qingguo"] = "倾国",
  [":sk_le__qingguo"] = "当其他角色使用【杀】或普通锦囊牌指定你为目标后，你可以弃置一张黑色手牌令此牌对你无效。若你弃置的牌为♠牌，"..
  "你可以令该角色失去1点体力。",
  ["sk_le__luoshen"] = "洛神",
  [":sk_le__luoshen"] = "准备阶段，你可以判定并获得生效后的判定牌，重复此流程，直到有判定牌点数重复。你于本回合内加此牌点数的手牌上限。",
  ["#sk_le__qingguo-discard"] = "倾国：你可以弃置一张黑色手牌，令 %dest 使用的%arg对你无效，若弃置♠牌，你可以令其失去1点体力",
  ["#sk_le__qingguo-invoke"] = "倾国：是否令 %dest 失去1点体力？",

  ["$sk_le__qingguo1"] = "",
  ["$sk_le__qingguo2"] = "",
  ["$sk_le__luoshen1"] = "",
  ["$sk_le__luoshen2"] = "",
  ["~sk_le__zhenji"] = "",
}

local lvbu = General(extension, "sk_le__lvbu", "qun", 4)
local sk_le__feijiang = fk.CreateViewAsSkill{
  name = "sk_le__feijiang",
  pattern = "slash",
  anim_type = "offensive",
  prompt = "#sk_le__feijiang",
  card_filter = Util.FalseFunc,
  view_as = function(self, cards)
    local card = Fk:cloneCard("slash")
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    local room = player.room
    local cards = player:getCardIds("h")
    local yes = table.find(cards, function (id)
      return Fk:getCardById(id).sub_type == Card.SubtypeWeapon
    end)
    player:throwAllCards("h")
    if not player.dead then
      player:drawCards(#cards, self.name)
    end
    use.extra_data = use.extra_data or {}
    use.extra_data.sk_le__feijiang = true
    if not player.dead then
      local choices = {"sk_le__feijiang2"}
      if table.find(TargetGroup:getRealTargets(use.tos), function (id)
        return not room:getPlayerById(id):isNude()
      end) then
        table.insert(choices, 1, "sk_le__feijiang1")
      end
      local choice
      if not yes then
        choice = room:askForChoice(player, choices, self.name)
      end
      if yes or choice == "sk_le__feijiang1" then
        for _, id in ipairs(TargetGroup:getRealTargets(use.tos)) do
          local to = room:getPlayerById(id)
          if not to.dead and not to:isNude() then
            to:addToPile(self.name, to:getCardIds("hej"), false, self.name)
          end
        end
      end
      if yes or choice == "sk_le__feijiang2" then
        for _, id in ipairs(TargetGroup:getRealTargets(use.tos)) do
          local to = room:getPlayerById(id)
          room:addPlayerMark(to, MarkEnum.SkInvalidity.."-turn", 1)
          room:addPlayerMark(to, "@@SkInvalidity-turn", 1)
        end
      end
      if yes then
        player:setSkillUseHistory(self.name, 0, Player.HistoryTurn)
      end
    end
  end,
  enabled_at_play = function(self, player)
    return not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  enabled_at_response = function(self, player, response)
    return not response and not player:isKongcheng() and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
}
local sk_le__feijiang_delay = fk.CreateTriggerSkill{
  name = "#sk_le__feijiang_delay",
  mute = true,
  events = {fk.TurnEnd, fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    if event == fk.TurnEnd then
      return #player:getPile("sk_le__feijiang") > 0
    elseif event == fk.DamageCaused then
      return data.to == player and player.room.logic:damageByCardEffect() and table.contains(data.card.skillNames, "sk_le__feijiang")
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    if event == fk.TurnEnd then
      player.room:moveCardTo(player:getPile("sk_le__feijiang"), Card.PlayerHand, player, fk.ReasonJustMove,
        "sk_le__feijiang", nil, false, player.id)
    elseif event == fk.DamageCaused then
      data.damage = data.damage * 2
    end
  end,
}
local sk_le__feijiang_targetmod = fk.CreateTargetModSkill{
  name = "#sk_le__feijiang_targetmod",
  bypass_times = function(self, player, skill, scope, card, to)
    return table.contains(card.skillNames, "sk_le__feijiang")
  end,
  bypass_distances =  function(self, player, skill, card, to)
    return table.contains(card.skillNames, "sk_le__feijiang")
  end,
}
sk_le__feijiang:addRelatedSkill(sk_le__feijiang_delay)
sk_le__feijiang:addRelatedSkill(sk_le__feijiang_targetmod)
lvbu:addSkill(sk_le__feijiang)
Fk:loadTranslationTable{
  ["sk_le__lvbu"] = "吕布",
  ["#sk_le__lvbu"] = "杀破万千",

  ["sk_le__feijiang"] = "飞将",
  [":sk_le__feijiang"] = "每回合限一次，当你需使用【杀】时，你可以弃置所有手牌并摸等量的牌，视为使用一张无距离和次数限制的【杀】，此【杀】"..
  "造成的伤害翻倍，使用前你选择一项：1.将目标角色区域内所有牌移出游戏直到回合结束；2.令目标角色技能无效直到回合结束。若你以此法弃置的牌"..
  "中有武器牌，改为依次执行两项，且视为本回合未发动本技能。",
  ["#sk_le__feijiang"] = "飞将：你可以弃置所有手牌，摸等量的牌，视为使用【杀】",
  ["sk_le__feijiang1"] = "目标所有牌移出游戏直到回合结束",
  ["sk_le__feijiang2"] = "目标所有技能失效直到回合结束",
  ["@@SkInvalidity-turn"] = "技能失效",
}

---摸牌阶段摸牌数+n
MarkEnum.SkDrawNCards = "SkDrawNCards"
local sk_extra_draw = fk.CreateTriggerSkill{
  name = "sk_extra_draw",
  global = true,

  refresh_events = {fk.DrawNCards},
  can_refresh = function (self, event, target, player, data)
    return target == player and player:getMark(MarkEnum.SkDrawNCards) ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    data.n = data.n + player:getMark(MarkEnum.SkDrawNCards)
  end,
}
Fk:addSkill(sk_extra_draw)

---所有技能失效
MarkEnum.SkInvalidity = "SkInvalidity"
local sk_invalidity = fk.CreateInvaliditySkill {
  name = "sk_invalidity",
  global = true,
  invalidity_func = function(self, from, skill)
    ---@param object Card|Player
    ---@param markname string
    ---@param suffixes string[]
    ---@return boolean
    local function hasMark(object, markname, suffixes)
      if not object then return false end
      for mark, _ in pairs(object.mark) do
        if mark == markname then return true end
        if mark:startsWith(markname .. "-") then
          for _, suffix in ipairs(suffixes) do
            if mark:find(suffix, 1, true) then return true end
          end
        end
      end
      return false
    end
    return from:hasSkill(skill, true) and
      skill:isPlayerSkill(from) and skill.visible and
      hasMark(from, MarkEnum.SkInvalidity, MarkEnum.TempMarkSuffix)
  end
}
Fk:addSkill(sk_invalidity)

return extension
